<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addCates">添加分类</el-button>
        </el-col>
      </el-row>

      <!-- 树形表格 -->
      <tree-table
        :data="catesList"
        :columns="columns"
        show-index
        :selection-type="false"
        :expand-type="false"
        border
      >
        <!-- 是否有效组件 -->
        <template slot="isOk" slot-scope="scope">
          <i
            class="el-icon-success"
            v-if="scope.row.cat_deleted === false"
            style="color: lightgreen"
          ></i>
          <i class="el-icon-error" v-else style="color: red"></i>
        </template>
        <!-- 排序组件 -->
        <template slot="sort" slot-scope="scope">
          <el-tag type="primary" v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag type="success" v-else-if="scope.row.cat_level === 1"
            >二级</el-tag
          >
          <el-tag type="warning" v-else>三级</el-tag>
        </template>
        <!-- 操作组件 -->
        <template slot="opt" slot-scope="scope">
          <el-button type="primary" @click="editCate(scope.row)">
            <i class="el-icon-edit"></i>
            修改
          </el-button>
          <el-button type="danger" @click="deleteCate(scope.row)">
            <i class="el-icon-delete"></i>
            删除
          </el-button>
        </template>
      </tree-table>

      <!-- 页码 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>

      <!-- 添加种类 -->
      <el-dialog
        title="添加种类"
        :visible.sync="addCateDialogVisible"
        width="50%"
        @close="closeAddCate"
      >
        <el-form
          :model="addCateForm"
          :rules="addCateFormRules"
          ref="addCateFormRef"
          label-width="100px"
        >
          <el-form-item label="分类名称" prop="cat_name">
            <el-input v-model="addCateForm.cat_name"></el-input>
          </el-form-item>
          <!-- 级联选择器 -->
          <!-- options 关联的数据 -->
          <!-- v-model 对应 选中的id数组 -->
          <!-- props 对应key value -->
          <el-form-item label="父级分类">
            <el-cascader
              :options="parentCatesList"
              :props="props"
              v-model="parentKeys"
              @change="handleChange"
              clearable
            ></el-cascader>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addCateDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addCateData">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 修改种类 -->
      <el-dialog
        title="修改种类"
        :visible.sync="editCateDialogVisible"
        width="50%"
        @close="closeEditCate"
      >
        <el-form
          :model="editCateForm"
          :rules="editCateFormRules"
          ref="editCateFormRef"
          label-width="100px"
        >
          <el-form-item label="分类名称" prop="cat_name">
            <el-input v-model="editCateForm.cat_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editCateDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editCateData">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 删除种类 -->
      <el-dialog
        title="确定要删除吗"
        :visible.sync="deleteCateDialogVisible"
        width="50%"
      >
        <span slot="footer" class="dialog-footer">
          <el-button @click="deleteCateDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="deleteCateData">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'Cate',
  data() {
    return {
      // 种类列表
      catesList: [],
      // 种类总数
      total: 0,
      // 查询信息
      queryInfo: {
        type: 3,
        //当前页码值
        pagenum: 1,
        // 每页多少条
        pagesize: 5,
      },
      // 表格各列的配置
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name',
        },
        {
          label: '是否有效',
          type: 'template',
          template: 'isOk',
        },
        {
          label: '排序',
          type: 'template',
          template: 'sort',
        },
        {
          label: '操作',
          type: 'template',
          template: 'opt',
        },
      ],
      // 是否开启添加种类对话框
      addCateDialogVisible: false,

      // 需要添加的类别信息
      addCateForm: {
        cat_pid: 0,
        cat_name: '',
        cat_level: 0,
      },
      // 需要添加的类别信息规则
      addCateFormRules: {
        cat_name: [
          { required: true, message: '分类名称不能为空', trigger: 'blur' },
        ],
      },
      // 父级分类列表
      parentCatesList: [],
      // 级联选择器选中项id
      parentKeys: [],
      // 配置选项
      props: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        checkStrictly: true,
      },

      // 修改的信息
      editCateForm: {
        id: '',
        cat_name: '',
      },
      // 修改的信息规则
      editCateFormRules: {
        cat_name: [
          { required: true, message: '分类名称不能为空', trigger: 'blur' },
        ],
      },
      // 是否打开修改的对话框
      editCateDialogVisible: false,

      // 删除的id
      deleteId: '',
      // 是否打开删除的对话框
      deleteCateDialogVisible: false,
    }
  },
  created() {
    this.getCatesList()
  },
  methods: {
    // 获取种类列表
    async getCatesList() {
      const { data: res } = await this.$http.get('categories', {
        params: this.queryInfo,
      })
      if (res.meta.status !== 200) this.$message.error('获取列表失败')
      this.catesList = res.data.result
      this.total = res.data.total
    },
    // 添加种类
    addCates() {
      // 获取父级列表
      this.getParentCatesList()
      this.addCateDialogVisible = true
    },
    // 每页显示条数发生改变
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getCatesList()
    },
    // 页码发生改变
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getCatesList()
    },
    // 获取父类分级列表函数
    async getParentCatesList() {
      const { data: res } = await this.$http.get('categories', {
        params: { type: 2 },
      })
      if (res.meta.status !== 200)
        return this.$message.error('获取父级列表失败')
      this.parentCatesList = res.data
    },

    // 级联选择器发生改变  改变新建类别的信息
    handleChange() {
      // 如果parentKeys的长度不为0 则有父级
      if (this.parentKeys.length !== 0) {
        // 如果长度为1则有一个父级 cat_level为1
        this.addCateForm.cat_pid = this.parentKeys[this.parentKeys.length - 1]
        this.addCateForm.cat_level = this.parentKeys.length
      } else {
        this.addCateForm.cat_pid = 0
        this.addCateForm.cat_level = 0
      }
    },
    // 添加新建类别
    addCateData() {
      this.$refs.addCateFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.post(
          'categories',
          this.addCateForm
        )
        if (res.meta.status !== 201) return this.$message.error('创建失败')

        this.$message.success('创建成功')
        this.getCatesList()
        this.addCateDialogVisible = false
      })
    },
    // 关闭添加种类的对话框
    closeAddCate() {
      this.addCateForm.cat_pid = 0
      this.addCateForm.cat_level = 0
      this.addCateForm.cat_name = ''
      this.parentKeys = []
    },

    // 点击修改按钮
    editCate(scope) {
      this.editCateDialogVisible = true
      this.editCateForm.id = scope.cat_id
      this.editCateForm.cat_name = scope.cat_name
    },
    // 关闭修改对话框
    closeEditCate() {
      this.editCateForm.id = ''
      this.editCateForm.cat_name = ''
    },
    // 修改分类
    editCateData() {
      this.$refs.editCateFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          `categories/${this.editCateForm.id}`,
          { cat_name: this.editCateForm.cat_name }
        )
        if (res.meta.status !== 200) return this.$message.error('修改失败')

        this.$message.success('修改成功')
        this.editCateDialogVisible = false
        this.getCatesList()
      })
    },
    // 点击删除按钮
    deleteCate(scope) {
      this.deleteCateDialogVisible = true
      this.deleteId = scope.cat_id
    },
    // 删除种类
    async deleteCateData() {
      const { data: res } = await this.$http.delete(
        `categories/${this.deleteId}`
      )
      if (res.meta.status !== 200) return this.$message.error('删除失败')

      this.$message.success('删除成功')
      this.deleteCateDialogVisible = false
      this.getCatesList()
    },
  },
}
</script>

<style lang="less" scoped>
.zk-table {
  margin-top: 15px;
}
.el-cascader {
  width: 100%;
}
</style>